package multiplex.dataaccess.dao;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import multiplex.dataaccess.DaoException;
import multiplex.model.Preco;

public class PrecoDao extends AbstractDao{
	
	public Preco getUnique() throws DaoException {
		try{
			PreparedStatement st = getConnection().prepareStatement("SELECT * FROM Preco");
			ResultSet rs = st.executeQuery();
			if(rs.next()){
				Preco preco = new Preco();
				fillPreco(preco, rs);
				st.close();
				return preco;
			}
		} catch(Exception e){
			throw new DaoException(e);
		}
		return null;
	}

	public void update(Preco preco) throws DaoException {
		try{
			PreparedStatement st = getConnection().prepareStatement(
					"UPDATE Preco SET precoSemana=?, precoFimDeSemana=?");
			fillPreparatedStatement(st, preco);
			st.execute();
			st.close();
		}catch(Throwable e){
			throw new DaoException(e);
		}
	}

	private void fillPreco(Preco preco, ResultSet rs) throws SQLException {
		preco.setId(rs.getInt("id"));
		preco.setPrecoSemana(rs.getDouble("precoSemana"));
		preco.setPrecoFimDeSemana(rs.getDouble("precoFimDeSemana"));
	}
	
	private void fillPreparatedStatement(PreparedStatement st, Preco preco) throws SQLException {
		st.setDouble(1, preco.getPrecoSemana());
		st.setDouble(2, preco.getPrecoFimDeSemana());
	}
	
	public void updatePrecoSemana(double preco) throws DaoException {
		try{
			PreparedStatement st = getConnection().prepareStatement(
					"UPDATE Preco SET precoSemana=?");
			st.setDouble(1, preco);
			st.execute();
			st.close();
		}catch(Throwable e){
			throw new DaoException(e);
		}
	}
	
	public void updatePrecoFimDeSemana(double preco) throws DaoException {
		try{
			PreparedStatement st = getConnection().prepareStatement(
					"UPDATE Preco SET precoFimDeSemana=?");
			st.setDouble(1, preco);
			st.execute();
			st.close();
		}catch(Throwable e){
			throw new DaoException(e);
		}
	}
}
